package spring.module.retry;

import java.time.LocalTime;
import java.util.SplittableRandom;

import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;

import lombok.extern.slf4j.Slf4j;

/**
 * 重试服务
 * 
 * @author Lucky Yang

 */
@Slf4j
@Service
public class RetryService {
    private SplittableRandom random = new SplittableRandom(47);

    /**
     * 业务方法
     * @param code
     * @return
     */
    @Retryable(value = {LessThanThreeException.class, GreaterThanSevenException.class}, maxAttempts = 3, backoff = @Backoff(delay = 2000, multiplier = 1.5))
    public String execute(String code) {
        log.info("{} 调用时间: {}", code, LocalTime.now());

        int num = random.nextInt(10);
        if (num < LessThanThreeException.THREE) {
            throw new LessThanThreeException();
        }
        if (num > GreaterThanSevenException.SEVEN) {
            throw new GreaterThanSevenException();
        }
        log.info("{} 成功", code);

        return code;
    }

    @Recover
    public String recover(LessThanThreeException e, String code) {
        log.info("回调方法: {}", e.getClass().getName());
        // 记日志到数据库 或者调用其余的方法
        return "400";
    }

    @Recover
    public String recover(GreaterThanSevenException e, String code) {
        log.info("回调方法: {}", e.getClass().getName());
        // 记日志到数据库 或者调用其余的方法
        return "400";
    }
}
